package com.abcode.nettyserversocketio.controller.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.abcode.nettyserversocketio.biz.IUserBizService;
import com.abcode.nettyserversocketio.common.Result;
import com.abcode.nettyserversocketio.gen.entity.FriendRequest;
import com.abcode.nettyserversocketio.gen.entity.User;
import com.abcode.nettyserversocketio.gen.param.UserParam;
import com.abcode.nettyserversocketio.gen.service.UserService;
import com.abcode.nettyserversocketio.gen.vo.FriendRequestVO;
import com.abcode.nettyserversocketio.gen.vo.UserVO;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequestMapping("/api/user")
@RestController
public class UserApiController extends BaseApiController{

    @Resource
    IUserBizService userBizService;
    @Resource
    UserService userService;

    @PostMapping("reg")
    public Result reg(@Valid @RequestBody UserParam userParam) {
        int count = 20;
        String username = userParam.getUsername();
        for (int i = 0; i < count; i++) {
            String tempName = username + "_" + i;
            userParam.setUsername(tempName);
            if(i==count-1){
                return userBizService.reg(userParam);
            }else {
                userBizService.reg(userParam);
            }
        }
        return Result.ok();
    }

    @PostMapping("login")
    public Result login(@Valid @RequestBody UserParam userParam){
        return userBizService.login(userParam);
    }
    @GetMapping("verifyToken")
    public Result verifyToken(@RequestHeader("Authorization") String token){
        if(StrUtil.isBlank(token)){
            return Result.error("token不能为空");
        }
        return userBizService.verifyToken(token);
    }

    /**
     * 获取好友列表
     * @return
     */
    @PostMapping("getAllFriends")
    public Result getAllFriend(@RequestHeader("Authorization") String token){
        UserVO userVO = userBizService.getUserVOByToken(token);
        if(ObjUtil.isEmpty(userVO)){
            return Result.error("登录过期，请重新登录。");
        }
        List<User> friendList = userBizService.getAllFriends(userVO.getId());
        List<UserVO> userVOList = friendList.stream().map(item->{
            UserVO userVO1 = new UserVO();
            BeanUtil.copyProperties(item, userVO1);
            return userVO1;
        }).collect(Collectors.toList());
        return Result.ok(userVOList);
    }

    @GetMapping("/getMuidUserInfo/{id}")
    public Result getMuidUserInfo(@PathVariable(name = "id") String id){
        UserVO userVO = null;
        User user = userService.getById(id);
        if(ObjUtil.isNotEmpty(user)){
            userVO = new UserVO();
            BeanUtil.copyProperties(user, userVO);
        }
        return Result.ok(userVO);
    }

    /**
     * 查找用户
     * @param paramMap
     * @return
     */
    @PostMapping("searchMUID")
    public Result searchMUID(@RequestBody Map<String,Object> paramMap){
        List<User> userList = userBizService.selectUser((String) paramMap.get("uuid"));
        List<UserVO> userVOList = userList.stream().map(item->{
            UserVO userVO1 = new UserVO();
            BeanUtil.copyProperties(item, userVO1);
            return userVO1;
        }).collect(Collectors.toList());
        return Result.ok(userVOList);
    }

    /**
     * 未查阅消息数量
     * @param token
     * @return
     */
    @PostMapping("getAllNoticesNumber")
    public Result getAllNoticesNumber(@RequestHeader("Authorization") String token){
        // TODO: 2023/6/18 消息数量
        UserVO userVO = userBizService.getUserVOByToken(token);
        if(ObjUtil.isEmpty(userVO)){
            return Result.error("登录过期，请重新登录。");
        }
        int count = userBizService.getAllNoticesNumber(userVO.getId());
        JSONObject jsonObject = new JSONObject();
        jsonObject.putOnce("number", count);
        return Result.ok(jsonObject);
    }

    /**
     * 查询未查阅消息列表
     * @param token
     * @return
     */
    @PostMapping("getAllNotices")
    public Result getAllNotices(@RequestHeader("Authorization") String token){
        // TODO: 2023/6/18 消息数量
        UserVO userVO = userBizService.getUserVOByToken(token);
        if(ObjUtil.isEmpty(userVO)){
            return Result.error("登录过期，请重新登录。");
        }
        List<FriendRequest> requestList = userBizService.getAllNotices(userVO.getId());
        List<FriendRequestVO> requestVOList = requestList.stream().map(item->{
            FriendRequestVO requestVO = new FriendRequestVO();
            BeanUtil.copyProperties(item, requestVO);
            return requestVO;
        }).collect(Collectors.toList());
        return Result.ok(requestVOList);
    }

    @GetMapping("/getPersonInfo/{id}")
    public Result getPersonInfo(@PathVariable(name = "id") String id){
        UserVO userVO = null;
        User user = userService.getById(id);
        if(ObjUtil.isNotEmpty(user)){
            userVO = new UserVO();
            BeanUtil.copyProperties(user, userVO);
        }
        return Result.ok(userVO);
    }

    /**
     * 判断是否是朋友关系
     * @param paramMap
     * @param token
     * @return
     */
    @PostMapping("isOwnFriend")
    public Result isOwnFriend(@RequestBody Map<String,String> paramMap, @RequestHeader("Authorization") String token){
        UserVO userVO = userBizService.getUserVOByToken(token);
        if(ObjUtil.isEmpty(userVO)){
            return Result.error("登录过期，请重新登录。");
        }
        String uuid = paramMap.get("muid");
        User relationUser = userBizService.getUserByUuid(uuid);
        boolean isFriend = userBizService.isOwnFriend(userVO.getId(), relationUser.getId());
        return Result.ok(isFriend);
    }

    /**
     * 发送好友申请
     * @param paramMap
     * @param token
     * @return
     */
    @PostMapping("addFriendRequest")
    public Result addFriendRequest(@RequestBody Map<String,String> paramMap, @RequestHeader("Authorization") String token){
        UserVO userVO = userBizService.getUserVOByToken(token);
        if(ObjUtil.isEmpty(userVO)){
            return Result.error("登录过期，请重新登录。");
        }
        Long toUserId = Long.valueOf(paramMap.get("toUserId"));
        String message = paramMap.get("message");

        boolean rst = userBizService.friendRequest(userVO, toUserId, message);
        if(rst){
            return Result.ok("添加好友成功");
        }else{
            return Result.error("添加好友失败");
        }
    }

    @GetMapping("getProfile/{filename}")
    public Result getProfile(@PathVariable(name = "filename") String filename){
        return Result.ok();
    }

    /**
     * 同意加好友
     * @param param
     * @return
     */
    @PostMapping("/agreeFriendRequest")
    public Result agreeFriendRequest(@RequestBody Map<String,String> param){
        Long friendRequestId = Long.valueOf(param.get("friendRequestId"));
        UserVO userVO = getLoginUser();
        Result rst = userBizService.agreeFriendRequest(userVO, friendRequestId);
        return rst;
    }
}
